#include "StdAfx.h"
#include "SingleLineEditUI.h"
#include "SingleLineEditWnd.h"

CSingleLineEditUI::CSingleLineEditUI(void): m_pWindow(NULL), m_uEditStyle(ES_AUTOHSCROLL), m_bReadOnly(false)
{
}

CSingleLineEditUI::~CSingleLineEditUI(void)
{
}

LPCTSTR CSingleLineEditUI::GetClass() const
{
	return _T("SingleLineEditUI");
}

UINT CSingleLineEditUI::GetControlFlags() const
{
	return UIFLAG_SETCURSOR | UIFLAG_TABSTOP;
}

void CSingleLineEditUI::Event(TEventUI& event)
{
	if( event.Type == UIEVENT_SETCURSOR )
	{
		if( IsEnabled() ) {
			::SetCursor(::LoadCursor(NULL, MAKEINTRESOURCE(IDC_IBEAM)));
			return;
		}
	}
	if( event.Type == UIEVENT_WINDOWSIZE )
	{
		if( m_pWindow != NULL ) m_pManager->SetFocus(NULL);
	}
	if( event.Type == UIEVENT_SETFOCUS ) 
	{
		if( IsEnabled() ) {
			m_pWindow = new CSingleLineEditWnd();
			ASSERT(m_pWindow);
			m_pWindow->Init(this);
		}
	}
	if( event.Type == UIEVENT_BUTTONDOWN && IsFocused() && m_pWindow == NULL ) 
	{
		// FIX: In the case of window having lost focus, editor is gone, but
		//      we don't get another SetFocus when we click on the control again.
		m_pWindow = new CSingleLineEditWnd();
		ASSERT(m_pWindow);
		m_pWindow->Init(this);
		return;
	}
	CControlUI::Event(event);
}

void CSingleLineEditUI::SetText(LPCTSTR pstrText)
{
	m_sText = pstrText;
	if( m_pManager != NULL ) m_pManager->SendNotify(this, _T("changed"));
	Invalidate();
}

void CSingleLineEditUI::SetReadOnly(bool bReadOnly)
{
	m_bReadOnly = bReadOnly;
	Invalidate();
}

bool CSingleLineEditUI::IsReadOnly() const
{
	return m_bReadOnly;
}

void CSingleLineEditUI::SetEditStyle(UINT uStyle)
{
	m_uEditStyle = uStyle;
	Invalidate();
}

SIZE CSingleLineEditUI::EstimateSize(SIZE /*szAvailable*/)
{
	return CStdSize(0, 12 + m_pManager->GetThemeFontInfo(UIFONT_NORMAL).tmHeight);
}

void CSingleLineEditUI::DoPaint(HDC hDC, const RECT& /*rcPaint*/)
{
	UINT uState = 0;
	if( IsFocused() ) uState |= UISTATE_FOCUSED;
	if( IsReadOnly() ) uState |= UISTATE_READONLY;
	if( !IsEnabled() ) uState |= UISTATE_DISABLED;
	CBlueRenderEngineUI::DoPaintEditBox(hDC, m_pManager, m_rcItem, m_sText, uState, m_uEditStyle, false);
}
